/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

import {
  CENTEREVENTS,
  EventsRes,
  pickedFaceData,
  SceneGraph,
} from '@amcax/base';
import { ctx2 } from '@app-cad/module';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { useTools } from '@app-cad/common/hooks/useTools';
import { CurvedBaseCommand, CurvedCmdDialogParams } from '@app-cad/types';
import { useAsyncEffect, useMemoizedFn } from 'ahooks';
import i18n from 'i18next';
import { useState } from 'react';
import { isEmpty, omitBy } from 'lodash';
import { eventCenterManager } from '@app-base/common/events/EventCenterManager';
import { PickableCommandForm } from '@app-base/common/components/command-form/pickable';
import { PickInputRJSFFormat } from '@app-base/common/components/command-form/constants';
import { RJSFSchema } from '@rjsf/utils';
import { getTempMesh } from '@app-base/common/utils/renderTempFace';
import { wsApi } from '@app-base/server';
import { SurfacePicker } from '@app-base/common/components/SurfacePicker';

type FormData = {
  bases?: pickedFaceData[];
  keep?: boolean;
  region?: number[];
  extend: string;
};

type Params = {
  bases: string[];
  keep: boolean;
  region?: number[];
  extend: string;
};

enum ExtendMode {
  NONE = 'none',
  TANGENCY = 'tangency',
  CURVATURE = 'curvature',
}

function CommandSurfaceTrim({ title, onClose, props }: CurvedCmdDialogParams) {
  const initData: FormData = {
    keep: true,
    extend: ExtendMode.TANGENCY,
    region: [],
  };
  const [formData, setFormData] = useState<FormData>(initData);
  const [tempRegions, setTempRegions] = useState<any[]>([]);
  const cadScene = ctx2.cadScene;
  const assisGroup = cadScene.toolsGroup;

  // 释放对象
  const releaseObjects = () => {
    assisGroup.clear();
    SceneGraph.emptyGroup(assisGroup);
    ctx2.viewer.requestRender();
  };

  const { picker } = useTools();

  useAsyncEffect(async () => {
    if (props == null) {
      setFormData(initData);
      return;
    }
    const params: Params = props.params;
    const { bases, extend, region, keep } = params;

    await initEditDependency([...bases]);

    setFormData({
      bases: bases.map(
        (surface) => picker.generatePickObjByPickID(surface) as pickedFaceData,
      ),
      keep: keep,
      region: region,
      extend: extend,
    });
  }, []);

  useAsyncEffect(async () => {
    assisGroup.clear();
    if (formData?.bases?.length > 1) {
      const { bases, keep, extend } = formData;
      const baseIds = bases.map((s) => s.meshId);
      const params = {
        c: 'CreateSurface',
        a: {
          bases: baseIds,
          keep: keep,
          extend: extend,
        },
        type: 'TrimEachOther',
        p: true,
      };
      // 需要单独调用接口得到临时面的返回信息
      const data = await wsApi.execCmd(params);
      if (data?.length > 0) {
        const meshArr = [];
        data.forEach((item) => {
          const mesh = getTempMesh(item);
          assisGroup.add(mesh);
          meshArr.push(mesh);
        });
        setTempRegions(meshArr);
        ctx2.viewer.requestRender();
      }
    }
  }, [formData?.bases]);

  const isFormDataValid = () => {
    const { bases, keep, region } = formData;

    if ((!keep && region.length === 0) || isEmpty(tempRegions)) {
      return false;
    }

    return bases?.length > 1;
  };

  const checkAndFinishDraw = async () => {
    if (!isFormDataValid()) {
      return;
    }

    await execute(false);

    releaseObjects();

    onClose();
  };

  const { initEditDependency, initingEdit, isLoading, confirmCommand } =
    useCommand('cmd-surface-splitter', {
      onClose,
      finishDraw: checkAndFinishDraw,
      commandName: 'CreateSurface',
      editDxid: props?.shape,
    });

  const execute = async (preview: boolean) => {
    const { bases, region, keep, extend } = formData;
    const baseIds = bases.map((s) => s.meshId);
    await confirmCommand(
      {
        a: {
          bases: baseIds,
          region: region,
          keep: keep,
          extend: extend,
        },
        type: 'TrimEachOther',
      },
      preview,
    );
  };

  const tempSurfacePick = useMemoizedFn((ev: EventsRes<PointerEvent>) => {
    if (tempRegions != null && ev.button.onLeft) {
      const rayCaster = ctx2.viewer.sceneSetup.createRaycaster(
        ev.mouse.x,
        ev.mouse.y,
      );

      const intersects = rayCaster.intersectObject(assisGroup, true);

      if (intersects.length > 0) {
        const ids = tempRegions?.map((item) => item?.name);
        const obj = intersects[0]?.object as any;
        const dxid = obj?.modelDxid;
        const index = ids?.indexOf(dxid);
        if (index > -1) {
          let region = formData?.region;
          // core的region从0开始
          region = region?.includes(index)
            ? region.filter((item) => item !== index)
            : [...region, index];
          const form = {
            ...formData,
            region: region,
          };

          setFormData(form);
        }
      }
    }
  });

  const onActiveFocus = () => {
    eventCenterManager.activeEventCenter.on(
      CENTEREVENTS.POINTERDOWN,
      tempSurfacePick,
    );
  };

  const onActiveBlur = () => {
    eventCenterManager.activeEventCenter.off(
      CENTEREVENTS.POINTERDOWN,
      tempSurfacePick,
    );
  };

  const onDialogClose = () => {
    releaseObjects();
    onClose();
  };

  const schema: RJSFSchema = {
    type: 'object',
    properties: omitBy(
      {
        bases: {
          type: 'array',
          items: {
            type: 'string',
            enum: [],
          },
          format: PickInputRJSFFormat.MultiPickFace,
          uniqueItems: true,
        },
        keep: {
          type: 'string',
          default: true,
          title: '保留选定区域',
          oneOf: [
            {
              title: '保留选定区域',
              const: true,
            },
            {
              title: '移除选定区域',
              const: false,
            },
          ],
        },
        region: {
          type: 'string',
          format: PickInputRJSFFormat.PickSurface,
        },
        extend: {
          type: 'string',
          default: ExtendMode.TANGENCY,
          title: '外插延伸类型',
          oneOf: [
            {
              title: '相切',
              const: ExtendMode.TANGENCY,
            },
            {
              title: '无',
              const: ExtendMode.NONE,
            },
            {
              title: '曲率',
              const: ExtendMode.CURVATURE,
            },
          ],
        },
      },
      (v) => !v,
    ),
  };

  return (
    <PickableCommandForm
      disabled={initingEdit}
      title={title}
      onClose={onDialogClose}
      submitLoading={isLoading}
      schema={schema}
      formData={formData}
      onChange={(v) => {
        setFormData(v);
      }}
      extraUiSchema={{
        bases: {
          'ui:placeholder': '选择要修剪的曲面',
          'ui:autofocus': true,
        },
        region: omitBy(
          {
            'ui:placeholder': '选择要保留或移除的面',
            'ui:widget': SurfacePicker,
          },
          (v) => v == null,
        ),
      }}
      onFocus={(id) => {
        if (id.replace('root_', '') === 'region') {
          onActiveFocus();
        }
      }}
      onBlur={(id) => {
        if (id.replace('root_', '') === 'region') {
          onActiveBlur();
        }
      }}
      submitText='完成'
      onSubmit={checkAndFinishDraw}
      isFormDataValid={isFormDataValid()}
    />
  );
}

export const cmdSurfaceTrim: CurvedBaseCommand = {
  id: 'CommandSurfaceTrim',
  label: 'command.surface-trim',
  icon: 'commands/curved/trim',
  create: (label, onClose, props) => (
    <CommandSurfaceTrim
      title={i18n.t(label)}
      onClose={onClose}
      props={props}
    />
  ),
};
